package com.etrans.web.gps.business.base.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.base.domain.SimCardVO;
import com.etrans.web.gps.business.base.service.SimCardService;
import com.etrans.web.gps.business.base.service.UnitService;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.common.page.ResultContans;
import com.etrans.web.gps.util.grid.FlexiGridUtil;

/**
 * sim卡
 * @author yin
 * 2017-07-02
 */
@Controller
@RequestMapping("/base/simcard/*")
public class SimCardController extends BaseController{
	@Autowired
	private SimCardService simCardService;
	@Autowired
	private UnitService unitService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping("querySimCardList.html")
	@ResponseBody
	public PageVo querySimCardList(@RequestParam  String paramsGrid){
		PageVo page = new PageVo();		
		Map<String, Object> paramMap =  FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		List<SimCardVO> simCartList = simCardService.querySimCardList(paramMap);		
		page.setRows(simCartList);
		page.setPage((int)paramMap.get("page"));
		page.setTotal(simCardService.querySimCardListCount(paramMap));
		return page;
	}
	
	// 新增Sim卡页面
	@RequestMapping(value = "initSimCard.html")
	@ResponseBody
	public ModelAndView initSimCard(@RequestParam Model model) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("action", "insert");
		mav.addObject("addSimCard", new SimCardVO());
		mav.setViewName("views/base/simcard/addSimCardForm");
		return mav;	
	}
	
	@RequestMapping(value = "initUpdateSimCard.html")
	@ResponseBody
	public ModelAndView initUpdateSimCard(@RequestParam  Integer simcardId) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("action", "update");
		mav.addObject("simcardId", simcardId);
		SimCardVO simcard = simCardService.querySimCardById(simcardId);
		mav.addObject("simcard", simcard);
		mav.setViewName("views/base/simcard/addSimCardForm");
		return mav;	
	}
	
	@RequestMapping(value = "updateSimCard.html")
	@ResponseBody
	public SimCardVO updateSimCard(@RequestParam  Integer simcardId) {
		try {
			// 查找相应的Sim卡
			SimCardVO simcard = simCardService.querySimCardById(simcardId);
			return simcard;
		} catch (Exception e) {
			//logger.error("", e);
			return null;
		}

	}
	
	@RequestMapping(value = "saveSimCard.html")
	@ResponseBody
	public Map<String,Object> saveSimCard(@RequestParam  String action, SimCardVO simcard) {
		Map<String,Object> result = new HashMap<>();
		try {
			//首先判断是否存在相同的电话号码，要保证电话号码唯一
	        HashMap<String, Object> parms=new HashMap<String, Object>();
	        parms.put("PhoneNO", simcard.getPhoneNO());
	    	if ("update".equals(action)) {
	    		parms.put("ID", simcard.getId());
	    	}
			int Count = simCardService.queryCountByPhoneNO(parms);
			if (Count == 0) {
				
				if ("insert".equals(action)) {
					// 默认是未使用
					simcard.setIsInUse(0);
					// 直接保存
					simCardService.saveSimCard(simcard);
				}

				if ("update".equals(action)) {
					simCardService.updateSimCard(simcard);
				}
				result.put("code", Constant.RETURN_OK_CODE);
			} else {
				// 已经重复
				result.put("code", Constant.RETURN_Repent_CODE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			//logger.error("", e);
			result.put("code", Constant.RETURN_ERROR_CODE);
			result.put("msg", "保存失败!");
		}
		return result;
	}
	
	// 删除Sim卡信息
	@RequestMapping(value = "delSimCard.html")
	@ResponseBody
	public Map delSimCard(@RequestParam  String SimCardIds) {
		Map result = new HashMap();
		try {
			SimCardVO simCard;
			int IfIsUse=0;
			if (SimCardIds != null && !"".equals(SimCardIds)) {
				String[] ArrayvehicleId = SimCardIds.split(",");
				for (String perID : ArrayvehicleId) {
					simCard=simCardService.querySimCardById(Integer.parseInt(perID));
					//判断是否开户
					   Integer	isIsUse=simCard.getIsInUse();
					   if(isIsUse==null){
						   isIsUse=0;
					   }
					   if(isIsUse.equals(1)){
					    	IfIsUse=1;
					   }else{
						   simCardService.deleteSimCardByID(Integer.parseInt(perID), request);
					   }
					}
					if(IfIsUse==0){
					    result.put("code",Constant.RETURN_OK_CODE);
					}else {
						result.put("code",Constant.RETURN_Repent_CODE);
					}
				}
		} catch (Exception e) {
			//logger.error("", e);
			e.printStackTrace();
			result.put("code",Constant.RETURN_ERROR_CODE);
			result.put("msg", "删除失败!");
		}
		return result;
	}
		
		/**
		 * 导出Sim卡信息
		 * @param response
		 * @param paramsGrid
		 * @param StartPage
		 * @param EndPage
		 */
		@SuppressWarnings("unchecked")
		@RequestMapping(value = "exportSimCards.html")
		public void exportSimCards(@RequestParam  HttpServletRequest request,HttpServletResponse response,String paramsGrid, String colModel, String title,String StartPage,String EndPage,String pagesize) {
			Map<String, Object> paramMap=getReqParameters();
			List<String> colModelList = JSON.parseObject(colModel, List.class);
			List<SimCardVO> list = simCardService.querySimCardExportList(paramMap);			
			List<HashMap<String, Object>> rows = new ArrayList<HashMap<String, Object>>();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			int start=Integer.valueOf(Integer.valueOf(StartPage)-1)*Integer.valueOf(pagesize);
			int end=Integer.valueOf(EndPage)*Integer.valueOf(pagesize);
			if(end>(list.size()-1)){
				end=list.size();
			}
			for(int i=start;i<end;i++){
				HashMap<String, Object> map = new HashMap<String, Object>();				
				
				SimCardVO obj=(SimCardVO)list.get(i);
				map.put("unitName", obj.getUnitName()==null ? "" : obj.getUnitName());
				map.put("phoneNO", obj.getPhoneNO()==null ? "" : String.valueOf(obj.getPhoneNO()));
				map.put("code", obj.getCode()==null ? "" : String.valueOf(obj.getCode()));
				map.put("isInUseStr", obj.getIsInUseStr()==null ? "" : String.valueOf(obj.getIsInUseStr()));
				map.put("soundKindStr", obj.getSoundKindStr()==null ? "" : String.valueOf(obj.getSoundKindStr()));
				map.put("isNoteStr", obj.getIsNoteStr()==null ? "" :  String.valueOf(obj.getIsNoteStr()));
				map.put("isTwoCitiesStr",obj.getIsTwoCitiesStr()==null ? "" : String.valueOf(obj.getIsTwoCitiesStr()));
				map.put("effectiveDate", obj.getEffectiveDate()==null ? "" : format.format(obj.getEffectiveDate()));
				map.put("buyDate", obj.getBuyDate()==null ? "" : format.format(obj.getBuyDate()));
				map.put("address", obj.getAddress()==null ? "" : String.valueOf(obj.getAddress()));
				map.put("prepaySum", obj.getPrepaySum()==null ? "" : String.valueOf(obj.getPrepaySum())+"");
				map.put("noteCount", obj.getNoteCount()==null ? "" : String.valueOf(obj.getNoteCount())+"");
				map.put("overSpend", obj.getOverSpend()==null ? "" :String.valueOf(obj.getOverSpend())+"");
				map.put("endDate", obj.getEndDate()==null ? "" : format.format(obj.getEndDate()));
				map.put("ip", obj.getIp()==null ? "" : String.valueOf(obj.getIp()));
				map.put("apn", obj.getApn()==null ? "" : String.valueOf(obj.getApn()));
				map.put("flux", obj.getFlux()==null ? "" : String.valueOf(obj.getFlux())+"");				
				rows.add(map);
			}
			int index=-1;
			List rowsList = new ArrayList<>();
			rowsList.add(rows);
			exportExl(request, response,title, removeHeadName(colModelList,index,-1),rowsList,null);
		}
		

		
		
		/**
		 * 查看是否存在sim卡号
		 * @param response
		 * @param PhoneNO
		 */
		@RequestMapping(value = "checkIfExistPhoneNO.html")
		@ResponseBody
		public Map<String, Object> checkIfExistPhoneNO(String PhoneNO) {
			Map<String, Object> result = new HashMap<>();
			HashMap<String, Object> parms = new HashMap<String, Object>();
			parms.put("PhoneNO", PhoneNO);
			int Count = simCardService.queryCountByPhoneNO(parms);
			if (Count == 0) {
				result.put("code", ResultContans.RETURN_OK_CODE.getCode());
			}else {
				result.put("code", ResultContans.RETURN_REPENT_CODE.getCode());
			}
			return result;
		}
		
		// 查询所有sim卡号
		@RequestMapping(value = "querySimCardsTrees.html")
		@ResponseBody
		public List querySimCardsTrees(@RequestParam  String WorkUnitID,String simID,String isInUse) {
			try {
				HashMap<String, Object> mapParams=new HashMap<String, Object>();
				mapParams.put("WorkUnitID", WorkUnitID);
				mapParams.put("simID", simID);
				mapParams.put("isInUse", isInUse);
				List rows = simCardService.querySimCardsTrees(mapParams);
				return rows;
			} catch (Exception e) {
				//logger.error("", e);
				e.printStackTrace();
				return new ArrayList();
			}
		}
}
